/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 权限管理器 - 处理音频播放相关权限请求
 */

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'ios_permission_helper.dart';

/// 权限管理器
/// 负责检查和请求音频播放相关权限
class PermissionManager {
  /// 单例模式
  static PermissionManager? _instance;
  static PermissionManager get instance {
    _instance ??= PermissionManager._internal();
    return _instance!;
  }

  PermissionManager._internal();

  /// 权限请求回调
  static Function(String message)? _onPermissionDenied;
  static Function(String message)? _onPermissionGranted;

  /// 设置权限回调
  static void setPermissionCallbacks({
    Function(String message)? onPermissionDenied,
    Function(String message)? onPermissionGranted,
  }) {
    _onPermissionDenied = onPermissionDenied;
    _onPermissionGranted = onPermissionGranted;
  }

  /// 请求音频播放相关权限
  Future<bool> requestAudioPermissions() async {
    try {
      debugPrint('PermissionManager: 开始请求音频播放权限');

      // 根据平台确定需要请求的权限列表
      final permissions = _getRequiredPermissions();

      if (permissions.isEmpty) {
        debugPrint('PermissionManager: 当前平台无需特殊权限');
        return true;
      }

      // 检查当前权限状态
      Map<Permission, PermissionStatus> currentStatuses = {};
      for (Permission permission in permissions) {
        try {
          currentStatuses[permission] = await permission.status;
        } catch (error) {
          debugPrint('PermissionManager: 检查权限状态失败 - $permission: $error');
          // iOS 平台某些权限可能无法检查，设置为 denied
          currentStatuses[permission] = PermissionStatus.denied;
        }
      }

      // 过滤出需要请求的权限
      List<Permission> permissionsToRequest = [];
      for (Permission permission in permissions) {
        final status = currentStatuses[permission] ?? PermissionStatus.denied;
        if (status != PermissionStatus.granted) {
          permissionsToRequest.add(permission);
        }
      }

      if (permissionsToRequest.isEmpty) {
        debugPrint('PermissionManager: 所有权限已授予');
        _onPermissionGranted?.call('所有权限已授予');
        return true;
      }

      debugPrint('PermissionManager: 需要请求的权限: $permissionsToRequest');

      // iOS 平台特殊处理：逐个请求权限以避免崩溃
      // 使用平台特定的权限请求方式
      Map<Permission, PermissionStatus> statuses = {};
      if (Platform.isIOS) {
        // iOS 平台使用专门的助手类处理权限请求
        statuses = await IOSPermissionHelper.instance
            .safeRequestPermissions(permissionsToRequest);
      } else {
        // Android 平台批量请求
        statuses = await permissionsToRequest.request();
      }

      // 检查结果
      List<Permission> deniedPermissions = [];
      List<Permission> permanentlyDeniedPermissions = [];

      for (Permission permission in permissionsToRequest) {
        final status = statuses[permission] ?? PermissionStatus.denied;
        if (status == PermissionStatus.denied) {
          deniedPermissions.add(permission);
        } else if (status == PermissionStatus.permanentlyDenied) {
          permanentlyDeniedPermissions.add(permission);
        }
      }

      // 处理权限请求结果
      if (deniedPermissions.isEmpty && permanentlyDeniedPermissions.isEmpty) {
        debugPrint('PermissionManager: 所有权限请求成功');
        _onPermissionGranted?.call('权限授予成功，可以正常使用音频功能');
        return true;
      } else {
        debugPrint('PermissionManager: 部分权限被拒绝');
        debugPrint('  - 被拒绝的权限: $deniedPermissions');
        debugPrint('  - 永久拒绝的权限: $permanentlyDeniedPermissions');

        // iOS 平台权限被拒绝时不算作错误，用户仍可使用基础功能
        if (Platform.isIOS) {
          debugPrint('PermissionManager: iOS平台权限被拒绝，但允许继续使用基础功能');
          return false; // 返回 false 但不抛出错误
        }

        // 处理权限被拒绝的情况
        await _handlePermissionDenied(
            deniedPermissions, permanentlyDeniedPermissions);
        return false;
      }
    } catch (error, stackTrace) {
      debugPrint('PermissionManager: 请求权限失败 - $error');
      debugPrint('StackTrace: $stackTrace');

      // iOS 平台权限请求失败时不调用错误回调，避免崩溃
      if (Platform.isIOS) {
        debugPrint('PermissionManager: iOS平台权限请求异常，但允许继续使用');
        return false;
      }

      _onPermissionDenied?.call('权限请求失败: $error');
      return false;
    }
  }

  /// 获取当前平台需要的权限列表
  List<Permission> _getRequiredPermissions() {
    List<Permission> permissions = [];

    if (Platform.isAndroid) {
      // Android 权限
      permissions.addAll([
        Permission.notification, // 通知权限（Android 13+）
      ]);

      // 检查 Android 版本，某些权限只在特定版本需要
      // 这里可以根据需要添加更多权限检查
    } else if (Platform.isIOS) {
      // iOS 权限
      permissions.addAll([
        Permission.notification, // 通知权限
      ]);
    }

    return permissions;
  }

  /// 处理权限被拒绝的情况
  Future<void> _handlePermissionDenied(
    List<Permission> deniedPermissions,
    List<Permission> permanentlyDeniedPermissions,
  ) async {
    String message = '';

    if (permanentlyDeniedPermissions.isNotEmpty) {
      message = '部分权限被永久拒绝，需要手动在设置中开启：\n';
      for (Permission permission in permanentlyDeniedPermissions) {
        message += '• ${_getPermissionDescription(permission)}\n';
      }
      message += '\n点击"去设置"按钮可跳转到应用设置页面';
      _onPermissionDenied?.call(message);
    } else if (deniedPermissions.isNotEmpty) {
      message = '需要以下权限才能正常使用音频功能：\n';
      for (Permission permission in deniedPermissions) {
        message += '• ${_getPermissionDescription(permission)}\n';
      }
      _onPermissionDenied?.call(message);
    }
  }

  /// 获取权限描述
  String _getPermissionDescription(Permission permission) {
    switch (permission) {
      case Permission.notification:
        return '通知权限 - 用于显示播放控制和歌曲信息';
      case Permission.audio:
        return '音频权限 - 用于播放音乐';
      case Permission.microphone:
        return '麦克风权限 - 用于音频处理';
      default:
        return permission.toString();
    }
  }

  /// 检查权限状态
  Future<bool> checkPermissions() async {
    try {
      final permissions = _getRequiredPermissions();

      if (permissions.isEmpty) {
        return true;
      }

      for (Permission permission in permissions) {
        final status = await permission.status;
        if (status != PermissionStatus.granted) {
          debugPrint(
              'PermissionManager: 权限未授予 - ${_getPermissionDescription(permission)}');
          return false;
        }
      }

      debugPrint('PermissionManager: 所有权限已授予');
      return true;
    } catch (error) {
      debugPrint('PermissionManager: 检查权限失败 - $error');
      return false;
    }
  }

  /// 检查特定权限状态
  Future<PermissionStatus> checkPermissionStatus(Permission permission) async {
    try {
      final status = await permission.status;
      debugPrint(
          'PermissionManager: ${_getPermissionDescription(permission)} 状态 - $status');
      return status;
    } catch (error) {
      debugPrint('PermissionManager: 检查权限状态失败 - $error');
      return PermissionStatus.denied;
    }
  }

  /// 检查通知权限
  Future<bool> checkNotificationPermission() async {
    try {
      final status = await Permission.notification.status;
      final isGranted = status == PermissionStatus.granted;
      debugPrint('PermissionManager: 通知权限状态 - $isGranted');
      return isGranted;
    } catch (error) {
      debugPrint('PermissionManager: 检查通知权限失败 - $error');
      return false;
    }
  }

  /// 请求通知权限
  Future<bool> requestNotificationPermission() async {
    try {
      final status = await Permission.notification.request();
      final isGranted = status == PermissionStatus.granted;
      debugPrint('PermissionManager: 通知权限请求结果 - $isGranted');
      return isGranted;
    } catch (error) {
      debugPrint('PermissionManager: 请求通知权限失败 - $error');
      return false;
    }
  }

  /// 显示权限说明对话框
  Future<void> showPermissionDialog(
    BuildContext context, {
    String? title,
    String? message,
    bool showSettingsButton = false,
  }) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(title ?? '需要权限'),
          content: SingleChildScrollView(
            child: Text(message ?? '应用需要相关权限才能正常工作'),
          ),
          actions: <Widget>[
            if (showSettingsButton) ...[
              TextButton(
                child: const Text('去设置'),
                onPressed: () {
                  Navigator.of(context).pop();
                  openSettings();
                },
              ),
            ],
            TextButton(
              child: const Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: const Text('重试'),
              onPressed: () {
                Navigator.of(context).pop();
                requestAudioPermissions();
              },
            ),
          ],
        );
      },
    );
  }

  /// 打开应用设置页面
  Future<bool> openSettings() async {
    try {
      // 使用 permission_handler 包的全局 openAppSettings 函数
      final opened = await openAppSettings();
      debugPrint('PermissionManager: 打开应用设置结果 - $opened');
      return opened;
    } catch (error) {
      debugPrint('PermissionManager: 打开应用设置失败 - $error');
      return false;
    }
  }

  /// 请求特定权限
  Future<bool> requestPermission(Permission permission) async {
    try {
      debugPrint(
          'PermissionManager: 请求权限 - ${_getPermissionDescription(permission)}');

      final status = await permission.request();
      final isGranted = status == PermissionStatus.granted;

      debugPrint('PermissionManager: 权限请求结果 - $isGranted');

      if (isGranted) {
        _onPermissionGranted
            ?.call('${_getPermissionDescription(permission)} 授予成功');
      } else {
        _onPermissionDenied
            ?.call('${_getPermissionDescription(permission)} 被拒绝');
      }

      return isGranted;
    } catch (error) {
      debugPrint('PermissionManager: 请求权限失败 - $error');
      _onPermissionDenied?.call('权限请求失败: $error');
      return false;
    }
  }

  /// 检查是否需要显示权限说明
  Future<bool> shouldShowPermissionRationale(Permission permission) async {
    try {
      final status = await permission.status;
      // 如果权限被拒绝但不是永久拒绝，则需要显示说明
      return status == PermissionStatus.denied;
    } catch (error) {
      debugPrint('PermissionManager: 检查权限说明失败 - $error');
      return false;
    }
  }

  /// 检查权限是否被永久拒绝
  Future<bool> isPermissionPermanentlyDenied(Permission permission) async {
    try {
      final status = await permission.status;
      return status == PermissionStatus.permanentlyDenied;
    } catch (error) {
      debugPrint('PermissionManager: 检查权限永久拒绝状态失败 - $error');
      return false;
    }
  }

  /// 获取权限状态描述
  String getPermissionStatusDescription(PermissionStatus status) {
    switch (status) {
      case PermissionStatus.granted:
        return '已授予';
      case PermissionStatus.denied:
        return '被拒绝';
      case PermissionStatus.restricted:
        return '受限制';
      case PermissionStatus.limited:
        return '有限授予';
      case PermissionStatus.permanentlyDenied:
        return '永久拒绝';
      default:
        return '未知状态';
    }
  }

  /// 初始化权限检查
  /// 在应用启动时调用
  Future<PermissionCheckResult> initializePermissions() async {
    try {
      debugPrint('PermissionManager: 开始初始化权限检查');

      // 检查当前权限状态
      final hasPermissions = await checkPermissions();
      final permissions = _getRequiredPermissions();

      Map<Permission, PermissionStatus> permissionStatuses = {};
      for (Permission permission in permissions) {
        try {
          permissionStatuses[permission] = await permission.status;
        } catch (error) {
          debugPrint('PermissionManager: 检查单个权限失败 - $permission: $error');
          // iOS 平台某些权限检查可能失败，设置为默认状态
          permissionStatuses[permission] = PermissionStatus.denied;
        }
      }

      final result = PermissionCheckResult(
        hasAllPermissions: hasPermissions,
        permissionStatuses: permissionStatuses,
      );

      if (!hasPermissions) {
        debugPrint('PermissionManager: 权限不足，需要请求权限');
        debugPrint('权限状态详情:');
        for (var entry in permissionStatuses.entries) {
          debugPrint(
              '  - ${_getPermissionDescription(entry.key)}: ${getPermissionStatusDescription(entry.value)}');
        }
      } else {
        debugPrint('PermissionManager: 权限检查通过');
      }

      return result;
    } catch (error, stackTrace) {
      debugPrint('PermissionManager: 初始化权限检查失败 - $error');
      debugPrint('StackTrace: $stackTrace');

      // iOS 平台权限检查失败时，返回一个允许继续使用的结果
      if (Platform.isIOS) {
        debugPrint('PermissionManager: iOS平台权限检查失败，但允许继续使用');
        return PermissionCheckResult(
          hasAllPermissions: true, // 设置为 true 允许直接进入应用
          permissionStatuses: {},
          error: null, // 不设置错误，避免显示错误页面
        );
      }

      return PermissionCheckResult(
        hasAllPermissions: false,
        permissionStatuses: {},
        error: error.toString(),
      );
    }
  }

  /// 批量检查权限状态
  Future<Map<Permission, PermissionStatus>> checkMultiplePermissions(
    List<Permission> permissions,
  ) async {
    try {
      Map<Permission, PermissionStatus> statuses = {};
      for (Permission permission in permissions) {
        statuses[permission] = await permission.status;
      }
      return statuses;
    } catch (error) {
      debugPrint('PermissionManager: 批量检查权限失败 - $error');
      return {};
    }
  }

  /// 获取所有需要的权限及其状态
  Future<Map<String, dynamic>> getPermissionReport() async {
    try {
      final permissions = _getRequiredPermissions();
      final statuses = await checkMultiplePermissions(permissions);

      Map<String, dynamic> report = {
        'platform': Platform.operatingSystem,
        'timestamp': DateTime.now().toIso8601String(),
        'permissions': {},
      };

      for (var entry in statuses.entries) {
        report['permissions'][_getPermissionDescription(entry.key)] = {
          'permission': entry.key.toString(),
          'status': entry.value.toString(),
          'statusDescription': getPermissionStatusDescription(entry.value),
          'isGranted': entry.value == PermissionStatus.granted,
        };
      }

      return report;
    } catch (error) {
      debugPrint('PermissionManager: 生成权限报告失败 - $error');
      return {
        'error': error.toString(),
        'timestamp': DateTime.now().toIso8601String(),
      };
    }
  }
}

/// 权限检查结果
class PermissionCheckResult {
  final bool hasAllPermissions;
  final Map<Permission, PermissionStatus> permissionStatuses;
  final String? error;

  const PermissionCheckResult({
    required this.hasAllPermissions,
    required this.permissionStatuses,
    this.error,
  });

  /// 获取被拒绝的权限
  List<Permission> get deniedPermissions {
    return permissionStatuses.entries
        .where((entry) => entry.value == PermissionStatus.denied)
        .map((entry) => entry.key)
        .toList();
  }

  /// 获取永久拒绝的权限
  List<Permission> get permanentlyDeniedPermissions {
    return permissionStatuses.entries
        .where((entry) => entry.value == PermissionStatus.permanentlyDenied)
        .map((entry) => entry.key)
        .toList();
  }

  /// 获取已授予的权限
  List<Permission> get grantedPermissions {
    return permissionStatuses.entries
        .where((entry) => entry.value == PermissionStatus.granted)
        .map((entry) => entry.key)
        .toList();
  }

  /// 是否有错误
  bool get hasError => error != null;

  @override
  String toString() {
    return 'PermissionCheckResult(hasAllPermissions: $hasAllPermissions, '
        'granted: ${grantedPermissions.length}, '
        'denied: ${deniedPermissions.length}, '
        'permanentlyDenied: ${permanentlyDeniedPermissions.length}, '
        'error: $error)';
  }
}
